package rwheel

import (
	"sync"
	"time"
)

const (
	precision = time.Millisecond * 50 //每轮间隔时间（误差时间）
)

var _lockTimerMap = sync.Mutex{}
var _timerMap = make(map[string]*_timerFunc)

var _lockTickerMap = sync.Mutex{}
var _tickerMap = make(map[string]*_tickerFunc)

func init() {
	go runTimer()
	go runTicker()
}

func runTimer() {
	ticker := time.NewTicker(precision)
	var allKey []string
	for {
		t := <-ticker.C
		_lockTimerMap.Lock()
		if len(_timerMap) > 0 {
			for k, v := range _timerMap {
				if t.UnixMilli() >= v.nextRunTime {
					allKey = append(allKey, k)
					go v.Run()
				}
			}
			if len(allKey) > 0 {
				for _, d := range allKey {
					delete(_timerMap, d)
				}
				allKey = nil
			}
		}
		_lockTimerMap.Unlock()
	}
}

func runTicker() {
	ticker := time.NewTicker(precision)
	for {
		t := <-ticker.C
		_lockTickerMap.Lock()
		if len(_tickerMap) > 0 {
			for _, v := range _tickerMap {
				if t.UnixMilli() >= v.nextRunTime {
					go v.Run(t)
				}
			}
		}
		_lockTickerMap.Unlock()
	}
}
